package com.iflyteck.boot;

import com.iflyteck.coder.RpcDecoder;
import com.iflyteck.handler.UserServiceHandler;
import com.iflyteck.json.JSONSerializer;
import com.iflyteck.pojo.RpcRequest;
import com.iflyteck.service.UserServiceImpl;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

// @Component
// public class InitServerBoot implements ApplicationRunner {
public class InitServerBoot {
//    @Resource
//    private UserServiceHandler handler;

    public static void startServer(Integer port) throws Exception {
        //1、创建两个线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        //2、创建服务端的启动引导类
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //3、配置启动引导对象
        serverBootstrap.group(bossGroup,workGroup)
                // 设置通道为Nio
                .channel(NioServerSocketChannel.class)
                // 创建监听channel
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        // 获取管道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        // 给管道对象pipeline设置编码
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class,new JSONSerializer()));
                        // 将将我们自定义的ChannelHandler添加到通道中
                        pipeline.addLast(new UserServiceHandler());
                    }
                });
        // 4、绑定端口
        serverBootstrap.bind("127.0.0.1", port).sync();
        System.out.println("服务启动");
    }
}
